package com.example.signin.ui.home

import android.graphics.Color
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.lifecycle.ViewModel
import androidx.recyclerview.widget.RecyclerView
import com.example.signin.R
import com.example.signin.bean.PersonBean
import com.example.signin.databinding.ItemRankingListBinding
import java.util.*
import kotlin.collections.HashMap

class HomeViewModel : ViewModel() {

    fun bindAdapter(recyclerView: RecyclerView, personBean: PersonBean) {
        val hashMap = HashMap<String, Float>()
        val map = HashMap<String,Float>()
        val arrive = HashMap<String, Float>()
        personBean.data.forEach {
            if (hashMap[it.department] != null) {
                hashMap[it.department] = hashMap[it.department]!!.plus(1f)
                if (it.isArrive == 1){
                    arrive[it.department] = arrive[it.department]!!.plus(1f)
                }
            } else {
                hashMap[it.department] = 1f
                arrive[it.department] = if (it.isArrive == 1) 1f else 0f
            }
        }
        hashMap.forEach { (s, i) ->
            val i1 = arrive[s]?:0f
            map[s] = i1/i * 100f
        }
        val infoIds: List<Map.Entry<String, Float>> = ArrayList<Map.Entry<String, Float>>(map.entries)
        Collections.sort(infoIds) { p0, p1 -> (p1.value - p0.value).toInt() }
        recyclerView.adapter = Adapter(infoIds)

    }
}

class Adapter(private val info: List<Map.Entry<String, Float>>) :
    RecyclerView.Adapter<Adapter.Holder>() {

    class Holder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        val itemBinding: ItemRankingListBinding = ItemRankingListBinding.bind(itemView)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): Holder {
        return Holder(
            LayoutInflater.from(parent.context).inflate(R.layout.item_ranking_list, parent, false)
        )
    }

    override fun onBindViewHolder(holder: Holder, position: Int) {
        holder.itemBinding.department.text = info[position].key
        holder.itemBinding.statisticsView.setData(info[position].value)
        holder.itemBinding.statisticsView.setColor(getRandColor())
    }

    override fun getItemCount(): Int {
        return info.size
    }

    private fun getRandColor(): Int {
        var R: String
        var G: String
        var B: String
        val random = Random()
        R = Integer.toHexString(random.nextInt(256)).uppercase(Locale.getDefault())
        G = Integer.toHexString(random.nextInt(256)).uppercase(Locale.getDefault())
        B = Integer.toHexString(random.nextInt(256)).uppercase(Locale.getDefault())
        R = if (R.length == 1) "0$R" else R
        G = if (G.length == 1) "0$G" else G
        B = if (B.length == 1) "0$B" else B
        return Color.parseColor("#$R$G$B")
    }
}